package studentInterface;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

import com.registerserver.model.Student;
import com.registerserver.service.IService;

public class UserInterface extends JFrame implements ActionListener
{
	JPanel panelStudentInfo, panelRegisterInfo, panelSubject, panelYearsTree, panelStudentImage
	, panelStudent, panelFunction;
	JTree treeCourse;
	JTable tblCourseNew, tblCourseOld;
	JLabel lblStudentName, lblBirthOfDate, lblStudentID, lblStudentSex, lblStudentPicture, lblCourseOld, lblCourseNew
	, lblYearsTree, lblPictureBox, lblStudentClass, lblStudentFaculty;
	JButton bntChangePass, bntViewResultTotalMarks, bntViewTimeTable, bntLogOut;
	Box boxInterface, boxStudentInfo, boxCourse;
	JScrollPane scrTreeCourse;
	Image imgPictureOfStudent;
	ImageIcon iconStudent, iconChangePass, iconViewResultTotalMarks, iconViewTimeTable, iconLogOut;
	BufferedImage bufferImage;
	DefaultMutableTreeNode treeNode = null;
	ChangePass frameChangePass = null;
	ViewTimeTable frameViewTimeTable = null;
	ViewResultTotalMarks frameViewResultTotalMarks = null;
	int width, height;
	Object[][] cellsCourseOld;
	Object[][] cellsCourseNew;
	String[] columnNames = { "Môn học", "Mã học phần", "Số tín chỉ", "Giảng viên", "Sĩ số", "Phòng học", "Bắt buộc", "HP yêu cầu" };
	int col = 8;
	String studentID;
	Context ctx;
	IService service = null;
	public UserInterface(String studentID, IService service) throws Exception
	{
		this.service = service;
		this.studentID = studentID;
		initialInterface();
	}

	public static void main(String[] args)
	{
		try{

			//new UserInterface("09095811").setVisible(true);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{

		if(e.getSource() == bntChangePass)
		{
			if(frameChangePass == null)
			{
				char[] password = null;
				String username = null;
				frameChangePass = new ChangePass(username, password);
				frameChangePass.setAlwaysOnTop(true);
				frameChangePass.setDefaultCloseOperation(HIDE_ON_CLOSE);
				frameChangePass.setVisible(true);
			}
			else if(frameChangePass.getDefaultCloseOperation() == HIDE_ON_CLOSE)
			{
				frameChangePass.setVisible(true);
			}
		}
		else if(e.getSource() == bntLogOut)
		{
			//Log out
			System.exit(1);
		}
		else if(e.getSource() == bntViewResultTotalMarks)
		{
			if(frameViewResultTotalMarks == null)
			{
				try {
					frameViewResultTotalMarks = new ViewResultTotalMarks(studentID, service);
					frameViewResultTotalMarks.setVisible(true);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			frameViewResultTotalMarks.setVisible(true);
		}
		else if(e.getSource() == bntViewTimeTable)
		{
			if(frameViewTimeTable == null)
			{
				try {
					String StudentID = null;
					frameViewTimeTable = new ViewTimeTable(StudentID);
					frameViewTimeTable.setVisible(true);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		//frameViewTimeTable.setVisible(true);
	}
	
	public int getScreenWorkingWidth() 
	{
	    return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
	}

	public int getScreenWorkingHeight()
	{
	    return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height - 5;
	}
	
	public void initialInterface() throws Exception
	{
		UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		width = getScreenWorkingWidth();
		height = getScreenWorkingHeight();
		setSize(width, height);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setResizable(false);
		setTitle("Register Subjects Online");
		boxInterface = Box.createVerticalBox();
		boxCourse = Box.createHorizontalBox();
		boxStudentInfo = Box.createHorizontalBox();
		bntChangePass = new JButton();
		bntChangePass.setToolTipText("Đổi mật khẩu");
		bntLogOut = new JButton();
		bntLogOut.setToolTipText("Thoát chương trình");
		bntViewResultTotalMarks = new JButton();
		bntViewResultTotalMarks.setToolTipText("Xem bảng điểm");
		bntViewTimeTable = new JButton();
		bntViewTimeTable.setToolTipText("Xem thời khóa biểu");
		panelStudentInfo = new JPanel();
		panelStudentImage = new JPanel();
		panelStudent = new JPanel();
		panelStudent.setPreferredSize(new Dimension(width / 5 - 10, height / 5));
		initlalLabelName();				
		initialIconImage();	
		panelStudentInfo.setPreferredSize(new Dimension(width * 3 / 5, height / 5 - 20));
		//panelStudentInfo.setBorder(BorderFactory.createLineBorder(Color.blue));
		panelStudentInfo.setLayout(new GridLayout(3, 3));
		panelStudentInfo.add(lblStudentName);
		panelStudentInfo.add(lblStudentID);
		panelStudentInfo.add(lblStudentClass);	
		panelStudentInfo.add(lblBirthOfDate);
		panelStudentInfo.add(lblStudentClass);
		panelStudentInfo.add(lblStudentSex);
		panelStudentInfo.add(lblStudentFaculty);
		panelStudent.add(panelStudentInfo);
		panelStudent.add(panelFunction);
		boxStudentInfo.setBorder(BorderFactory.createLineBorder(Color.black));	
		panelYearsTree = new JPanel();
		panelYearsTree.setPreferredSize(new Dimension(width / 5, (height * 4) / 5));
		panelYearsTree.add(lblYearsTree);
		boxCourse.add(panelYearsTree);	  
		panelSubject = new JPanel();
		panelSubject.setPreferredSize(new Dimension((width * 4) / 5, (height * 4) / 5));
		boxCourse.add(panelSubject);	
		////////////////////////////////////////		
		initialTableSubject();
		tblCourseNew_Clicked();
		initialTreeCourse();
		tblCourseOld_Clicked();
		boxStudentInfo.add(panelStudent);
		boxCourse.add(panelSubject);
		boxInterface.add(boxStudentInfo);
		boxInterface.add(boxCourse);
		boxInterface.add(boxCourse);
		add(boxInterface);
		
		bntChangePass.addActionListener(this);
		bntLogOut.addActionListener(this);
		bntViewResultTotalMarks.addActionListener(this);
		bntViewTimeTable.addActionListener(this);
	}
	private void initialTreeCourse()
	{	
		treeNode = new DefaultMutableTreeNode("Năm học");
		for(int i = 1; i < 5; i++)
		{
			DefaultMutableTreeNode year = new DefaultMutableTreeNode("Năm " + i);
			treeNode.add(year);
			for(int j = 1; j < 4; j++)
			{
				DefaultMutableTreeNode semester = new DefaultMutableTreeNode("Học kỳ " + j);
				year.add(semester);
			}
			//treeCourse.add(year);
		}
		treeCourse = new JTree(treeNode);
		treeCourse.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		scrTreeCourse = new JScrollPane(treeCourse);
		scrTreeCourse.setPreferredSize(new Dimension(width / 5, (height * 4) / 5));
		panelYearsTree.add(scrTreeCourse);
		treeCourse.addTreeSelectionListener(new TreeSelectionListener() {
		    public void valueChanged(TreeSelectionEvent e) 
		    {
		        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
		        		treeCourse.getLastSelectedPathComponent();
		        if (node == null) return;  /* if nothing is selected */ 
		    /* retrieve the node that was selected */ 
		        Object nodeInfo = node.getUserObject();
		    /* React to the node selection. */
		        try {
					//loadDataToTable(nodeInfo.toString());
		        	System.out.println(nodeInfo);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		    }
		});
	}
	private void initlalLabelName() throws Exception
	{
		Student student = service.getStudentInfoByID(studentID);
		Font font = new Font("Arial", Font.BOLD, 13);
		lblCourseNew = new JLabel("Lớp học phần chưa đăng ký");
		lblCourseNew.setFont(font);
		lblCourseOld = new JLabel("Lớp học phần đã đăng ký");
		lblCourseOld.setFont(font);
		lblBirthOfDate = new JLabel("Năm sinh ");
		lblBirthOfDate.setFont(font);
		lblYearsTree = new JLabel("Thời gian học tập ");
		lblYearsTree.setFont(font);
		lblStudentName = new JLabel("Họ và tên ");
		lblStudentName.setFont(font);
		lblStudentID = new JLabel("Mã sinh viên ");
		lblStudentID.setFont(font);
		lblStudentClass = new JLabel("Lớp ");
		lblStudentClass.setFont(font);
		lblStudentSex = new JLabel("Giới tính ");
		lblStudentSex.setFont(font);
		lblStudentFaculty = new JLabel("Khoa ");
		lblStudentFaculty.setFont(font);
		lblBirthOfDate.setText("Ngày sinh" + student.getBirthday());
		lblStudentClass.setText("Lớp " + student.getClassName());
		lblStudentID.setText("Mã sinh vien " + student.getID());
		lblStudentName.setText("Họ và tên  " + student.getLastName() + student.getFirstName());
		if(student.getSex().equals("male"))
			lblStudentSex.setText("Giới tính Nam");
		else
			lblStudentSex.setText("Giới tính Nữ");
		lblStudentFaculty.setText("Khoa " + student.getFacultyID());
	}
	private void initialIconImage() throws Exception
	{
		bufferImage = ImageIO.read(new File("resources/Image/Lee_Min_Ho.jpg"));
		panelFunction = new JPanel();
		//Add a Jlabel to display Student's Image
		Image scaledImage = bufferImage.getScaledInstance(width / 10, width / 10, Image.SCALE_SMOOTH);
		iconStudent = new ImageIcon(scaledImage);		
		lblPictureBox = new JLabel(iconStudent);
		panelStudentImage.setPreferredSize(new Dimension(width / 5 - 10, height / 5));
		panelStudentImage.add(lblPictureBox);
		panelStudent.add(panelStudentImage);
		
		//Khởi tạo các icon
		//Button changepass
		bufferImage = ImageIO.read(new File("resources/Image/Key.jpg"));
		scaledImage = bufferImage.getScaledInstance(width / 20 - 10, width / 20 - 10, Image.SCALE_SMOOTH);
		iconChangePass = new ImageIcon(scaledImage);
		bntChangePass.setIcon(iconChangePass);
		panelFunction.setPreferredSize(new Dimension(width / 5 - 20, height / 5- 20));
		panelFunction.setLayout(new GridLayout(2, 2));
		panelFunction.add(bntChangePass);
		//panelFunction.setBorder(BorderFactory.createLineBorder(Color.blue));
		
		//Button logout
		bufferImage = ImageIO.read(new File("resources/Image/logout.png"));
		scaledImage = bufferImage.getScaledInstance(width / 20 - 10, width / 20 - 10, Image.SCALE_SMOOTH);
		iconLogOut = new ImageIcon(scaledImage);
		bntLogOut.setIcon(iconLogOut);
		panelFunction.add(bntLogOut);
		
		bufferImage = ImageIO.read(new File("resources/Image/mark.jpg"));
		scaledImage = bufferImage.getScaledInstance(width / 20 - 10, width / 20 - 10, Image.SCALE_SMOOTH);
		iconViewResultTotalMarks = new ImageIcon(scaledImage);
		bntViewResultTotalMarks.setIcon(iconViewResultTotalMarks);
		panelFunction.add(bntViewResultTotalMarks);
		
		bufferImage = ImageIO.read(new File("resources/Image/timetable.jpg"));
		scaledImage = bufferImage.getScaledInstance(width / 20 - 10, width / 20 - 10, Image.SCALE_SMOOTH);
		iconViewTimeTable = new ImageIcon(scaledImage);
		bntViewTimeTable.setIcon(iconViewTimeTable);
		panelFunction.add(bntViewTimeTable);
	}
	private void initialTableSubject() throws Exception
	{
		panelSubject.add(lblCourseNew);
		loadDataToTableCourseNew();
		tblCourseNew = new JTable(cellsCourseNew, columnNames){
		    public boolean isCellEditable(int rowIndex, int colIndex) {
		        return false;   //Disallow the editing of any cell
		    }
		};
		tblCourseNew.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane scrCourseNew = new JScrollPane(tblCourseNew);
		scrCourseNew.setBorder(BorderFactory.createLineBorder(Color.black));
		scrCourseNew.setPreferredSize(new Dimension((width * 4) / 5 - 10, ((height * 4) / 10) - 35));
		panelSubject.add(scrCourseNew);
		
		loadDataToTableCourseOld();
		panelSubject.add(lblCourseOld);
		tblCourseOld = new JTable(cellsCourseOld, columnNames){
		    public boolean isCellEditable(int rowIndex, int colIndex) {
		        return false;   //Disallow the editing of any cell
		    }
		};
		tblCourseOld.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane scrCourseOld = new JScrollPane(tblCourseOld);
		scrCourseOld.setBorder(BorderFactory.createLineBorder(Color.black));
		scrCourseOld.setPreferredSize(new Dimension((width * 4) / 5 - 10, (height * 4) / 10 - 45));
		panelSubject.add(scrCourseOld);
		
		panelSubject.setBorder(BorderFactory.createLineBorder(Color.black));
		panelYearsTree.setBorder(BorderFactory.createLineBorder(Color.black));
	}
	
	private void loadDataToTableCourseOld() throws Exception
	{
		//
		//System.out.println(student.getFirstName());
		//if(student == null)
		{
			cellsCourseOld = new Object[1][col];
			cellsCourseOld[0][0] = "Không có dữ liệu";
			cellsCourseOld[0][1] = "Không có dữ liệu";
			cellsCourseOld[0][2] = "Không có dữ liệu";
			cellsCourseOld[0][3] = "Không có dữ liệu";
			cellsCourseOld[0][4] = "Không có dữ liệu";
			cellsCourseOld[0][5] = "Không có dữ liệu";
			cellsCourseOld[0][6] = "Không có dữ liệu";
			cellsCourseOld[0][7] = "Không có dữ liệu";
		}
		//else
		{
			System.out.println("k null");

		}
	}
	private void loadDataToTableCourseNew() throws Exception
	{
		//ResultSet rs = null;
		//Thực hiện gán rs ở đây
		//if(rs == null)
		{
			cellsCourseNew = new Object[1][col];
			cellsCourseNew[0][0] = "Không có dữ liệu";
			cellsCourseNew[0][1] = "Không có dữ liệu";
			cellsCourseNew[0][2] = "Không có dữ liệu";
			cellsCourseNew[0][3] = "Không có dữ liệu";
			cellsCourseNew[0][4] = "Không có dữ liệu";
			cellsCourseNew[0][5] = "Không có dữ liệu";
			cellsCourseNew[0][6] = "Không có dữ liệu";
			cellsCourseNew[0][7] = "Không có dữ liệu";
		}
		/*else
		{
				int _row = 0;
				cellsCourseNew[_row][0] = rs.getString(1);
				cellsCourseNew[_row][1] = rs.getString(2);
				cellsCourseNew[_row][2] = rs.getString(3);
				cellsCourseNew[_row][3] = rs.getString(4);
				cellsCourseNew[_row][4] = rs.getString(5);
				_row++;
		}*/
	}
	private void tblCourseNew_Clicked() throws Exception
	{
		tblCourseNew.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseClicked(MouseEvent e){
				int row = tblCourseNew.getSelectedRow();
				if(row != -1)
				{
					System.out.println("Click " + tblCourseNew.getValueAt(row, 1));
					// Xử lý thêm vào db, load lại table
					try {
						loadDataToTableCourseNew();
						loadDataToTableCourseOld();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
	}
	private void tblCourseOld_Clicked()
	{
		tblCourseOld.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseClicked(MouseEvent e) {
				int row = tblCourseOld.getSelectedRow();
				if(row != -1)
				{
					System.out.println("Click " + tblCourseOld.getValueAt(row, 1));
				}
			}
		});
	}
}
